from rest_framework import serializers
from users.models import User, Area, Address


def mobile_validate(data):
    # 前端传过来的手机号
    # 独立校验器
    # raise serializers.ValidationError('手机号重复')  # 有错就抛出异常
    # 没错就返回数据
    return data


class UserSerializer(serializers.ModelSerializer):
    # 重新设定字段, 替换掉模型中的设定, 重新设定地址的长度为5
    # mobile = serializers.CharField(max_length=11, validators=[mobile_validate])
    # 用户id,   只读字段
    # 用户密码,  只写字段
    # 单一字段验证, 验证地址
    def validate_mobile(self, data):
        # if data == '测试':
        #     raise serializers.ValidationError('请填写实际地址')  # 有错就抛出异常
        return data  # 没错就返回结果

    # def validate_phone(self, data):
    #     # 不符合手机号格式
    #     # raise serializers.ValidationError('手机号格式不正确')
    #     model = self.root.Meta.model
    #     num = model.objects.filter(phone=data).count()
    #     if num > 0:
    #         raise serializers.ValidationError('手机号已存在')
    #     return data

    def validate(self, attrs):
        # 所有属性验证器,   attrs中有所有的数据,
        # 1. 密码, 重复密码,
        if attrs.get('pw')!=attrs.get('pw2'):
            raise serializers.ValidationError('两遍密码不正确')  # 有问题报错
        # self.context 中有request和view上下文
        # self.context['view'].action 可以取到动作
        # attrs 是需要序列化的数据
        # raise serializers.ValidationError('xxx错误')  # 有问题报错
        return attrs  # 没问题返回数据

    class Meta:
        model = User
        # fields = ('id','username', ) # 临时添加字段也需要写在这里
        fields = '__all__'  # 所有字段
        # exclude = ['password']  # 排除 id 字段
        read_only_fields = ('id',)  # 指定字段为 read_only,

        # extra_kwargs = {}  # 局部替换某些字段的设定, 或者新增设定
        extra_kwargs = {
            "mobile": {  # 字段名, 为mobile字段整配置
                "min_length": 5,  # 给地址增加 最小长度限制
                "default": '13312341234',  # 增加默认值
            }
        }
        # 统一处理接口文档中的字段描述
        # for field in model._meta.fields:
        #     if extra_kwargs.get(field.attname, None):
        #         extra_kwargs[field.attname]['help_text'] = field.verbose_name
        #     else:
        #         extra_kwargs[field.attname] = {'help_text': field.verbose_name}


# 1. 定义模型序列化器
# class UserSerializer(serializers.ModelSerializer):
#     class Meta:
#         model = User
#         fields = ('id', 'username', 'mobile', 'email', 'email_active', 'default_address')
#         # fields = '__all__'  # 所有字段
#         # exclude = ['password']  # 排除 id 字段


class AreaSerializer(serializers.ModelSerializer):
    class Meta:
        model = Area
        fields = '__all__'


class AddressSerializer(serializers.ModelSerializer):
    class Meta:
        model = Address
        fields = ['id',
                  "title",
                  "receiver",
                  "place",
                  "mobile",
                  "tel",
                  "user",
                  "province", "city", "district",
                  "province_name",
                  "city_name",
                  "district_name",
                  "is_deleted"
                  ]
